﻿using System;
using System.Collections;
using System.Linq;
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;

public class MovingObject : MonoBehaviour
{
    [SerializeField]
    private Transform path;
    private Vector3[] forwardWaypoints;
    private Vector3[] backwardWaypoints;

    [SerializeField]
    private float moveSpeed = 1f;
    
    private float puaseTime;
    private SpriteRenderer statusHolder;
    private NPCStatuses activedStatus, deactivetedStatus;

    private bool isActivated;
    private bool isForward;

    NPCAnimationController animController;

    private void Start()
    {
        var query = from Transform child in path
                    select child.position;
        forwardWaypoints = query.ToArray();
        backwardWaypoints = (Vector3[])forwardWaypoints.Clone();
        Array.Reverse(backwardWaypoints);
        animController = GetComponent<NPCAnimationController>();

        isActivated = false;
        isForward = true;
    }

    public void Initialize(float time, SpriteRenderer holder, NPCStatuses ac, NPCStatuses deac)
    {
        puaseTime = time;
        statusHolder = holder;
        activedStatus = ac;
        deactivetedStatus = deac;

        statusHolder.sprite = StatusUIManager.Instance.GetSpriteByStatusEnum(deactivetedStatus);
    }

    public void OnActivate()
    {
        // TODO: NPC总是在反复调用这个函数，所以在这里做判断，只允许启动一次
        // 同时，我觉得这个脚本不需要NPC的启动，自己可以独立运行。
        // 建议自动移动相关的功能都在这一个类里完成，减少依赖。

        if (isActivated)
            return;
        isForward = true;
        GoForward();
        isActivated = true;
    }

    private void GoForward()
    {
        gameObject.tag = "Stun";
        statusHolder.sprite = StatusUIManager.Instance.GetSpriteByStatusEnum(activedStatus);
        transform.DOPath(forwardWaypoints, moveSpeed)
            .SetSpeedBased()
            .SetEase(Ease.Linear).OnComplete(Pause);
        SetAnimMovingStatus(true);
    }

    private void GoBackward()
    {
        gameObject.tag = "Stun";
        statusHolder.sprite = StatusUIManager.Instance.GetSpriteByStatusEnum(deactivetedStatus);
        transform.DOPath(backwardWaypoints, moveSpeed)
            .SetSpeedBased()
            .SetEase(Ease.Linear).OnComplete(Pause);
        SetAnimMovingStatus(true);
    }

    private void Pause()
    {
        gameObject.tag = "Untagged";
        StartCoroutine(HandleGo());
        SetAnimMovingStatus(false);
    }

    private IEnumerator HandleGo()
    {
        yield return new WaitForSeconds(puaseTime);

        isForward = !isForward;

        if (isForward)
        {
            GoForward();
        }
        else
        {
            GoBackward();
        }
    }

    private void SetAnimMovingStatus(bool isMoving)
    {
        if(animController != null)
        {
            animController.SetMovingStatus(isMoving);
        }
    }
}